package com.itsv.news.utils;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.itsv.news.bean.RssChannelBase;
import com.itsv.news.bean.RssChannelFeed;
import com.itsv.news.bean.RssChannelSub;

public class ChannelParseHandler extends DefaultHandler {
	private static final String TAG_CHANNEL = "channel";
	private static final String TAG_ITEM = "channel-sub";
	private static final String TAG_TITLE = "title";
	private static final String TAG_LINK = "link";
	private static final String TAG_DESCRIPTION = "description";
	private static final String ATTR_ID = "id";
	
	private RssChannelFeed mRssFeed;
	private RssChannelBase mRssChannelBase;
	private RssChannelSub mRssChannelSub;
	
	boolean mIsSubItem = false;
	
	private String mValue;
	private String mPreTag;
	
	/**
	 * 
	 * @return
	 */
	public RssChannelFeed getRssChannelFeed(){
		return mRssFeed;
	}
	
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		mRssFeed = new RssChannelFeed();
		mRssFeed.setmRssChannelList(new ArrayList<RssChannelBase>());
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if(TAG_CHANNEL.equals(localName)) {//channel
			mRssChannelBase = new RssChannelBase();
			mRssChannelBase.setItemList(new ArrayList<RssChannelSub>());
		}else if(TAG_ITEM.equals(localName)){
			mIsSubItem = true;
			mRssChannelSub = new RssChannelSub();
//			//获取item的id
			if(attributes.getValue(ATTR_ID) != null){
				mRssChannelSub.setId(attributes.getValue(ATTR_ID));
			}
		}
		
		mPreTag = localName;
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		String data = new String(ch,start,length);
		if(TAG_DESCRIPTION.equals(mPreTag) || TAG_LINK.equals(mPreTag) 
				|| TAG_TITLE.equals(mPreTag)){
			mValue = data;
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(TAG_CHANNEL.equals(localName)){//local
			mRssFeed.getmRssChannelList().add(mRssChannelBase);
		}else if(TAG_ITEM.equals(localName)){
			mRssChannelBase.getItemList().add(mRssChannelSub);
			mIsSubItem = false;
		}else if(TAG_DESCRIPTION.equals(localName)){
			if(mIsSubItem){
				mRssChannelSub.setDescription(mValue);
			}else {
				mRssChannelBase.setDescription(mValue);
			}
		}else if(TAG_TITLE.equals(localName)){
			if(mIsSubItem){
				mRssChannelSub.setTitle(mValue);
			}else {
				mRssChannelBase.setTitle(mValue);
			}
		}else if(TAG_LINK.equals(localName)){
				mRssChannelSub.setLink(mValue);
		}
		
		mValue = "";
		mPreTag = "";
	}
	
	@Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.endDocument();
    }
}